package com.fingard.dsp.bank.directbank.wjzf02;

import cacps.DownloadFileService;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IStatement;
import com.fingard.dsp.bank.directbank.wjzf02.hessian.CCPMDownloadClient;
import com.fingard.dsp.bank.reqrespobj.statement.ReqQryStatement;
import com.fingard.dsp.bank.reqrespobj.statement.RetAtsStatement;
import com.fingard.dsp.bank.reqrespobj.statement.TransState;
import com.fingard.dsp.bank.reqrespobj.statement.detail.RetAtsStatementDetail;
import com.fingard.text.StringHelper;

import java.util.ArrayList;

/**
 * 金联万家(WJZF02)对账单获取
 */
public class WJZF02Statement extends WJZF02Base implements IStatement {
	@Override
	public RetAtsStatement d_Qry_Statement(ReqQryStatement p_reqQrySttm) throws Exception {
		RetAtsStatement retAts = new RetAtsStatement(p_reqQrySttm);
		retAts.writeStart();
		
		String[] singleRespHeader = new String[]{"",""};
		String singleTotalNum = "0";
		
		String[] batRespHeader = new String[]{"",""};
		String batTotalNum = "0";
		
		boolean ennableActNoMapping = getBankConfig().getValueAsBool("ennableActNoMapping");
		if (ennableActNoMapping) {
			String mappingValue = getBankConfig().getMapValueByKey("billActNoMapping", p_reqQrySttm.actNum);
			if ("singleBill".equals(mappingValue)) {
				singleRespHeader = getSingleStatement(p_reqQrySttm, retAts);
				singleTotalNum = getTotalNum(retAts.totalNum);
			} else if ("batBill".equals(mappingValue)) {
				batRespHeader = getBatStatement(p_reqQrySttm, retAts);
				batTotalNum = getTotalNum(retAts.totalNum);
			} else {
				retAts.writeRespCode("-1");
				retAts.writeRespInfo("对账单账号所属交易类型值为空,请检查config.xml中'billActNoMapping'相关配置!");
				retAts.writeEnd();
				return retAts;
			}
		} else {
			singleRespHeader = getSingleStatement(p_reqQrySttm, retAts);
			singleTotalNum = getTotalNum(retAts.totalNum);
			
			batRespHeader = getBatStatement(p_reqQrySttm, retAts);
			batTotalNum = getTotalNum(retAts.totalNum);
		}

		if ("-1".equals(singleRespHeader[0]) && "-1".equals(batRespHeader[1])) {
			retAts.writeRespCode("-1");
			retAts.writeRespInfo("单笔代收付对账单获取失败,原因:[" + singleRespHeader[1] + "];" + "批量代收付对账单获取失败,原因:[" + batRespHeader[1] + "]");
		} else {
			if (retAts.getWrittenRdCount() == 0) {
				retAts.writeRespCode("0");
				String respInfo = singleRespHeader[1];
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = batRespHeader[1];
				}
				if (StringHelper.isNullOrEmpty(respInfo)) {
					respInfo = "交易为空!";
				}
				retAts.writeRespInfo(respInfo);
			} else {
				retAts.isWritedTotalNum(String.valueOf(Integer.parseInt(singleTotalNum) + Integer.parseInt(batTotalNum)));
			}
		}
		
		retAts.writeEnd();
		return retAts;
	}

	/**
	 * 单笔代收付对账单获取
	 * 
	 * @param p_reqQrySttm
	 *            ReqQryStatement
	 * @param retAts
	 *            RetAtsStatement
	 * @return
	 */
	public String[] getSingleStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) {
		String[] tmpRespHeader = new String[] { "", "" };

		String tmpRespCode = "-1";
		String tmpRespInfo = "";

		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if (actItem != null) {
				String cropNo = actItem.corpCode;
				String bizDate = p_reqQrySttm.busDate;

				String transCode = "";
				if ("F".equals(p_reqQrySttm.statementType) || "F".equals(actItem.billType)) {
					transCode = "20601";
				} else if ("S".equals(p_reqQrySttm.statementType) || "S".equals(actItem.billType)) {
					transCode = "20602";
				} else {
					transCode = "20601,20602";
				}

				if (transCode.contains(",")) {
					String[] tranCodeArray = transCode.split(",");
					for (String tranCode : tranCodeArray) {
						DownloadFileService service = new CCPMDownloadClient().getDownloadFileService(bankFront.serverDownload);

						byte[] tmpBytesResp = null;
						String useNewQryStatement = getBankConfig().getValueAsString("useNewQryStatement");
						if ("true".equals(useNewQryStatement.toLowerCase())) {
							tmpBytesResp = service.carryBackRealBalanceAccDataSpecial(cropNo, bizDate, tranCode);
							WriteBankLogLn2("发送银行：" + "carryBackRealBalanceAccDataSpecial 单笔同步对账方法： " + "cropNo :" + cropNo + "  bizDate:" + bizDate + " tranCode:" + tranCode);
						} else {
							tmpBytesResp = service.carryBackRealtimesBalanceAccountData(cropNo, bizDate, tranCode);
							WriteBankLogLn2("发送银行：" + "carryBackRealtimesBalanceAccountData 单笔同步对账方法： " + "cropNo :" + cropNo + "  bizDate:" + bizDate + " tranCode:" + tranCode);
						}

						String tmpStrRet = new String(tmpBytesResp, getCharset());
						WriteBankLogStep3(tmpStrRet);

						if ("error-system error".equals(tmpStrRet)) {
							tmpRespInfo = "接口调用出错";
						} else if ("error-invalid tranCode".equals(tmpStrRet)) {
							tmpRespInfo = "代收付标识错误";
						} else if ("error-no data".equals(tmpStrRet)) {
							tmpRespInfo = "没有业务数据";
						} else {
							ArrayList<ArrayList<String>> list = spitXml(tmpStrRet);
							if (list.size() > 0) {
								tmpRespCode = "0";
								
                                for (int i = 0; i < list.size(); i++) {
                                    ArrayList<String> result = list.get(i);
                                    String transState = result.get(8);
                                    if ("00".equals(transState)) {
                                        totalNum++;

                                        RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                                        tmpRetDetail.oppActName = result.get(2);
                                        tmpRetDetail.oppAct = result.get(3);
                                        tmpRetDetail.oppBank = result.get(4);
                                        tmpRetDetail.amount = result.get(5);
                                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTimeFormat.parse(result.get(1)));
                                        tmpRetDetail.askNumber = result.get(6);

                                        String bkSeq = result.get(7);
                                        if (!"null".equals(bkSeq)) {
                                            tmpRetDetail.bkSeq = bkSeq;
                                        }

                                        //20601(代付)或20602(代收)；
                                        if ("20601".equals(tranCode)) {
                                            tmpRetDetail.cdFlag = "27";
                                        } else {
                                            tmpRetDetail.cdFlag = "22";
                                        }

                                        tmpRetDetail.transState = TransState.Success;

                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
							} else {
								tmpRespCode = "-1";
								tmpRespInfo = "返回文件内容无总交易单数";
							}
						}
					}
				} else {
					DownloadFileService service = new CCPMDownloadClient().getDownloadFileService(bankFront.serverDownload);
					byte[] tmpBytesResp = service.carryBackRealtimesBalanceAccountData(cropNo, bizDate, transCode);
					WriteBankLogLn2("发送银行：" + "carryBackRealtimesBalanceAccountData 单笔同步对账方法： " + "cropNo :" + cropNo + "  bizDate:" + bizDate + " tranCode:" + transCode);

					String tmpStrRet = new String(tmpBytesResp, getCharset());
					WriteBankLogLn2("单笔对账单响应数据:\r\n" + tmpStrRet);

					if ("error-system error".equals(tmpStrRet)) {
						tmpRespInfo = "接口调用出错";
					} else if ("error-invalid tranCode".equals(tmpStrRet)) {
						tmpRespInfo = "代收付标识错误";
					} else if ("error-no data".equals(tmpStrRet)) {
						tmpRespInfo = "没有业务数据";
					} else {
						ArrayList<ArrayList<String>> list = spitXml(tmpStrRet);
						if (list.size() > 0) {
							tmpRespCode = "0";
							
                            for (int i = 0; i < list.size(); i++) {
                                ArrayList<String> result = list.get(i);
                                String transState = result.get(8);
                                if ("00".equals(transState)) {
                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();

                                    tmpRetDetail.oppActName = result.get(2);
                                    tmpRetDetail.oppAct = result.get(3);
                                    tmpRetDetail.oppBank = result.get(4);
                                    tmpRetDetail.amount = result.get(5);
                                    tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTimeFormat.parse(result.get(1)));
                                    tmpRetDetail.askNumber = result.get(6);

                                    //20601(代付)或20602(代收)；
                                    if ("20601".equals(transCode)) {
                                        tmpRetDetail.cdFlag = "27";
                                    } else {
                                        tmpRetDetail.cdFlag = "22";
                                    }

                                    String bkSeq = result.get(7);
                                    if (!"null".equals(bkSeq)) {
                                        tmpRetDetail.bkSeq = bkSeq;
                                    }
                                    tmpRetDetail.transState = TransState.Success;
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = "单笔账单内容无明细数据!";
						}
					}
				}
			} else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRespCode = "-1";
			tmpRespInfo = ex.getMessage();
			this.WriteBankLogLn(ex);
		}
		
		retAts.totalNum = String.valueOf(totalNum);

		tmpRespHeader[0] = tmpRespCode;
		tmpRespHeader[1] = tmpRespInfo;

		return tmpRespHeader;
	}

	/**
	 * 批量代收付对账单获取
	 * 
	 * @param p_reqQrySttm
	 * @param retAts
	 * @return
	 */
	public String[] getBatStatement(ReqQryStatement p_reqQrySttm, RetAtsStatement retAts) {
		String[] tmpRespHeader = new String[] { "", "" };

		String tmpRespCode = "-1";
		String tmpRespInfo = "";

		retAts.totalNum = "0";
		int totalNum = 0;

		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_reqQrySttm.actNum, "");
			if (actItem != null) {
				String cropNo = actItem.corpCode;
				String bizDate = p_reqQrySttm.busDate;

				String transCode = "";
				if ("F".equals(p_reqQrySttm.statementType) || "F".equals(actItem.billType)) {
					transCode = "40501";
				} else if ("S".equals(p_reqQrySttm.statementType) || "S".equals(actItem.billType)) {
					transCode = "40502";
				} else {
					transCode = "40501,40502";
				}
				if (transCode.contains(",")) {
					String[] tranCodeArray = transCode.split(",");
					for (String tranCode : tranCodeArray) {
						DownloadFileService service = new CCPMDownloadClient().getDownloadFileService(bankFront.serverDownload);
						byte[] tmpBytesResp = service.carryBackBalanceAccountData(cropNo, bizDate, tranCode);
						WriteBankLogLn2("发送银行：" + "carryBackBalanceAccountData 批量同步对账方法： " + "cropNo :" + cropNo + "  bizDate:" + bizDate + " tranCode:" + tranCode);

						String tmpStrRet = new String(tmpBytesResp, getCharset());
						WriteBankLogLn2("批量对账单响应数据:\r\n" + tmpStrRet);

						if ("error-system error".equals(tmpStrRet)) {
							tmpRespInfo = "接口调用出错";
						} else if ("error-invalid tranCode".equals(tmpStrRet)) {
							tmpRespInfo = "代收付标识错误";
						} else if ("error-no data".equals(tmpStrRet)) {
							tmpRespInfo = "没有业务数据";
						} else {
							boolean useActNoMatch = getBankConfig().getValueAsBool("useActNoMatch");
							
							ArrayList<ArrayList<String>> list = spitXml(tmpStrRet);
							if (list.size() > 0) {
								tmpRespCode = "0";

                                for (int i = 0; i < list.size(); i++) {
                                    ArrayList<String> result = list.get(i);
                                    String transState = result.get(7);
                                    if ("00".equals(transState)) {
                                        if (useActNoMatch) {
                                            if (p_reqQrySttm.actNum.equals(result.get(11))) {
                                                totalNum++;
                                            }
                                        } else {
                                            totalNum++;
                                        }

                                        RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                        tmpRetDetail.oppActName = result.get(2);
                                        tmpRetDetail.oppAct = result.get(3);
                                        tmpRetDetail.oppBank = result.get(4);
                                        tmpRetDetail.amount = result.get(5);
                                        if (result.get(1).contains("-")) {
                                            tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTimeFormat.parse(result.get(1)));
                                        } else {
                                            tmpRetDetail.busTime = Format.DateTime14Format.format(Format.Date8Format.parse(result.get(1)));
                                        }
                                        tmpRetDetail.askNumber = result.get(10);
                                        tmpRetDetail.reqBatchNO = result.get(6);
                                        boolean busiTime = getBankConfig().getValueAsBool("subBusitime");
                                        if (busiTime) {
                                            tmpRetDetail.busTime = tmpRetDetail.reqBatchNO.substring(0,8) + "000000";
                                        }
                                        tmpRetDetail.transState = TransState.Success;

                                        //代付设置40501，代收设置40502；
                                        if ("40501".equals(tranCode)) {
                                            tmpRetDetail.cdFlag = "27";
                                        } else {
                                            tmpRetDetail.cdFlag = "22";
                                        }
                                        retAts.writeRetDetail(tmpRetDetail);
                                    }
                                }
							} else {
								tmpRespCode = "-1";
								tmpRespInfo = "批次账单内容无明细数据!";
							}
						}
					}
				} else {
					DownloadFileService service = new CCPMDownloadClient().getDownloadFileService(bankFront.serverDownload);
					byte[] tmpBytesResp = service.carryBackBalanceAccountData(cropNo, bizDate, transCode);
					WriteBankLogLn2("发送银行：" + "carryBackBalanceAccountData 批量同步对账方法： " + "cropNo :" + cropNo + "  bizDate:" + bizDate + " tranCode:" + transCode);

					String tmpStrRet = new String(tmpBytesResp, getCharset());
					WriteBankLogLn2("批量对账单响应数据:\r\n" + tmpStrRet);

					if ("error-system error".equals(tmpStrRet)) {
						tmpRespInfo = "接口调用出错";
					} else if ("error-invalid tranCode".equals(tmpStrRet)) {
						tmpRespInfo = "代收付标识错误";
					} else if ("error-no data".equals(tmpStrRet)) {
						tmpRespInfo = "没有业务数据";
					} else {
						ArrayList<ArrayList<String>> list = spitXml(tmpStrRet);
						if (list.size() > 0) {
							tmpRespCode = "0";

                            for (int i = 0; i < list.size(); i++) {
                                ArrayList<String> result = list.get(i);
                                String transState = result.get(7);
                                if ("00".equals(transState)) {
                                    totalNum++;

                                    RetAtsStatementDetail tmpRetDetail = new RetAtsStatementDetail();
                                    tmpRetDetail.oppActName = result.get(2);
                                    tmpRetDetail.oppAct = result.get(3);
                                    tmpRetDetail.oppBank = result.get(4);
                                    tmpRetDetail.amount = result.get(5);
                                    if (result.get(1).contains("-")) {
                                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.DateTimeFormat.parse(result.get(1)));
                                    } else {
                                        tmpRetDetail.busTime = Format.DateTime14Format.format(Format.Date8Format.parse(result.get(1)));
                                    }
                                    tmpRetDetail.askNumber = result.get(10);
                                    tmpRetDetail.reqBatchNO = result.get(6);
                                    boolean busiTime = getBankConfig().getValueAsBool("subBusitime");
                                    if (busiTime) {
                                        tmpRetDetail.busTime = tmpRetDetail.reqBatchNO.substring(0,8) + "000000";
                                    }
                                    tmpRetDetail.transState = TransState.Success;

                                    //代付设置40501，代收设置40502；
                                    if ("40501".equals(transCode)) {
                                        tmpRetDetail.cdFlag = "27";
                                    } else {
                                        tmpRetDetail.cdFlag = "22";
                                    }
                                    retAts.writeRetDetail(tmpRetDetail);
                                }
                            }
						} else {
							tmpRespCode = "-1";
							tmpRespInfo = "批次账单内容无明细数据!";
						}
					}
				}
			} else {
				tmpRespCode = "-1";
				tmpRespInfo = "未找到账号[" + p_reqQrySttm.actNum + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRespCode = "-1";
			tmpRespInfo = ex.getMessage();
			this.WriteBankLogLn(ex);
		}
		
		retAts.totalNum = String.valueOf(totalNum);

		tmpRespHeader[0] = tmpRespCode;
		tmpRespHeader[1] = tmpRespInfo;

		return tmpRespHeader;
	}
}